from django.contrib.auth.backends import ModelBackend
import re
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from .models import *
from django.conf import settings


def get_user(username):
    try:
        if re.match("^1[345789]\d{9}$",username):
            user = User.objects.get(phone_number=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    return user


class CustomModelBackend(ModelBackend):
    """重新定义模型类"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        """重新改写判定用户方法"""
        user = get_user(username)
        if user and user.check_password(password):
            return user


def get_url(email,username):
    """对url进行加密"""
    serializer = Serializer(settings.SECRET_KEY,expires_in=60*60*24)
    url_str = serializer.dumps({"email":email,"username":username})
    url_str = url_str.decode()
    url = "http://www.meiduo.site:8000/verify_email?token=%s" % url_str
    return url


def analysis_url(data):
    """解析加密的url"""
    serializer = Serializer(settings.SECRET_KEY, expires_in=60 * 60 * 24)
    try:
        data_dict = serializer.loads(data)
        email = data_dict.get("email")
        username = data_dict.get("username")
        return email,username
    except:
        return None


